/*
 * Copyright (c) 2015. kupat Corporation. All rights reserved.
 *  see statement on http://www.kupat.cn.
 */
package com.kfgj.hkp.common.utils;

import com.kfgj.hkp.common.logging.Logger;
import com.kfgj.hkp.common.logging.LoggerFactory;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by liwensihan on 2014/11/7.
 *
 * @author liwensihan
 */
public class GenericsUtils {

    private static final Logger logger = LoggerFactory.getLogger(GenericsUtils.class);

    public static Class getSuperClassGenricType(Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    public static Class getSuperClassGenricType(Class clazz, int index) {
        Type genType = clazz.getGenericSuperclass();
        if (!(genType instanceof ParameterizedType)) {
            logger.warn(String.format("%s的父类非泛型类", clazz.getSimpleName()));
            return Object.class;
        }
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        if (index >= params.length || index < 0) {
            logger.warn(String.format("索引: %s 超出了%s 的泛型参数长度:%s", new Object[]{index, clazz.getSimpleName(), params.length}));
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            logger.warn(String.format("%s在父类的泛型参数中不是真正的Class类型", clazz.getSimpleName()));
            return Object.class;
        }
        return (Class) params[index];
    }

}
